/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.isystem.autpart.controller;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.isystem.autpart.beans.TCaracteristicasArticulo;
import org.isystem.autpart.beans.TCategoriaArticulo;
import org.isystem.autpart.beans.TClaseArticulo;
import org.isystem.autpart.beans.TTipoCaracteristica;
import org.isystem.autpart.dao.DAO;
import org.isystem.autpart.util.idNew;
import org.zkoss.bind.ValidationContext;
import org.zkoss.bind.Validator;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.bind.validator.AbstractValidator;

/**
 *
 * @author miguel-lap
 */
public class ManagerAdmArticulo {
    
    private static final long serialVersionUID = 1L;
    private List<TCategoriaArticulo> articulos = new LinkedList<TCategoriaArticulo>();
    private List<TClaseArticulo> clases = new LinkedList<TClaseArticulo>();
    private List<TCaracteristicasArticulo> caracteristicas = new LinkedList<TCaracteristicasArticulo>();
    private List<TTipoCaracteristica> tipos = new LinkedList<TTipoCaracteristica>();
    private TCategoriaArticulo articulo = new TCategoriaArticulo();
    private TCaracteristicasArticulo caracteristica = new TCaracteristicasArticulo();
    private TCaracteristicasArticulo caracteristicaSelected = new TCaracteristicasArticulo();
    private TTipoCaracteristica tipoSelected = new TTipoCaracteristica();
    private TCategoriaArticulo articuloSelected = new TCategoriaArticulo();
    private TClaseArticulo claseSelected = new TClaseArticulo();
    private DAO dao = new DAO();
    private boolean verSave;
    private boolean verSaveCA;
    private boolean mostrarAdd;
    private boolean mostrarAddCA;
    private boolean mostrarCA;
    private String saveLabel;
    private String saveLabelCA;
    private String buscar;
    private String buscarCA;
    private String val="";
    private String error="";
    private String valCA="";
    
    private Session s;
    
    //validators
    
    //validation messages
    Map<String, String> validationMessages = new HashMap<String,String>();
    
    @Init
    public void init(){
        System.out.println("Inicia AdminArticulo");
        s = dao.getSession();
        actualizaListaArticulos(s,"");
        mostrarAdd = false;
        mostrarCA = false;
        mostrarAddCA = false;
    }
    
    //Validators
    public Validator getFormValidator(){
        System.out.println("validator all");
        return new AbstractValidator() {
//            private HashMap validationMessages;

            public void validate(ValidationContext ctx) {
// Consultar si es persona natural o juridica
                String val = (String)ctx.getProperties("nombre")[0].getValue();
                System.out.println("denominacion "  + val);
//                ValidationMessages vmsgs = (ValidationMessages) ctx.getValidatorArg("vmsgs");
//                validationMessages.put("usuarioTextBox", "value1 error");
//                ctx.setInvalid(); // mark invalid
//                ValidationMessages vmsgs = ((BinderCtrl)ctx.getBindContext().getBinder()).getValidationMessages();
//                addInvalidMessage(ctx, "usuario", "value1 error");
//                System.out.println("111");
//                ctx.getBindContext().getBinder().notifyChange(validationMessages, "usuarioTextBox");
//                if(invalidCondition01(val)){
//                    addInvalidMessage(ctx, "fkey1", "value1 error");
//                }
//                val = (String)ctx.getProperties("value2")[0].getValue();
//                if(invalidCondition02(val)){
//                    addInvalidMessage(ctx, "fkey2", "value2 error");
//                }
//                val = (String)ctx.getProperties("value3")[0].getValue();
//                if(invalidCondition03(val)){
//                    addInvalidMessage(ctx, "fkey3", "value3 error");
//                }
//                ctx.getBindContext().getBinder().notifyChange(validationMessages, "usuarioTextBox");
                
                
            }
        };
    }
    public Validator getFormValidatorCA(){
        System.out.println("validator all");
        return new AbstractValidator() {
//            private HashMap validationMessages;

            public void validate(ValidationContext ctx) {
// Consultar si es persona natural o juridica
//                String val = (String)ctx.getProperties("denominacion")[0].getValue();
//                System.out.println("denominacion "  + val);
//                ValidationMessages vmsgs = (ValidationMessages) ctx.getValidatorArg("vmsgs");
//                validationMessages.put("usuarioTextBox", "value1 error");
//                ctx.setInvalid(); // mark invalid
//                ValidationMessages vmsgs = ((BinderCtrl)ctx.getBindContext().getBinder()).getValidationMessages();
//                addInvalidMessage(ctx, "usuario", "value1 error");
//                System.out.println("111");
//                ctx.getBindContext().getBinder().notifyChange(validationMessages, "usuarioTextBox");
//                if(invalidCondition01(val)){
//                    addInvalidMessage(ctx, "fkey1", "value1 error");
//                }
//                val = (String)ctx.getProperties("value2")[0].getValue();
//                if(invalidCondition02(val)){
//                    addInvalidMessage(ctx, "fkey2", "value2 error");
//                }
//                val = (String)ctx.getProperties("value3")[0].getValue();
//                if(invalidCondition03(val)){
//                    addInvalidMessage(ctx, "fkey3", "value3 error");
//                }
//                ctx.getBindContext().getBinder().notifyChange(validationMessages, "usuarioTextBox");
                
                
            }
        };
    }
    
    // botones
    @Command
    @NotifyChange({"verSave","val","articulo","mostrarAdd","saveLabel","clases", "claseSelected","mostrarCA","mostrarAddCA"})
    public void onClickadd() {
        System.out.println("click en agregar");
        articulo = new TCategoriaArticulo();
        actualizaListaClases(s, "");
        claseSelected = new TClaseArticulo();
        val="";
        mostrarAdd = true;
        mostrarAddCA = false;
        mostrarCA = false;
        verSave = true;
        val="";
        saveLabel ="Guardar";
    }
    // botones
    
    
    @Command
    @NotifyChange({"verSaveCA","valCA","caracteristica","mostrarAddCA","saveLabelCA","tipos","tipoSelected"})
    public void onClickaddCA() {
        System.out.println("click en agregar caracteristica");
        caracteristica = new TCaracteristicasArticulo();
        caracteristica.setTTipoCaracteristica(new TTipoCaracteristica());
        actualizaListaTipos(s, "");
        tipoSelected = new TTipoCaracteristica();
        valCA="";
        mostrarAddCA = true;
        verSaveCA = true;
        saveLabelCA ="Guardar";
    }
    
    @Command
    @NotifyChange({"articulos", "buscar","mostrarCA","mostrarAdd","mostrarAddCA"})
    public void onClickSearch() {
        System.out.println("click search");
        actualizaListaArticulos(s, " where a.nombre like '%"+buscar+"%'");
    }
    
    @Command
    @NotifyChange({"caracteristicas", "buscarCA"})
    public void onClickSearchCA() {
        System.out.println("click search");
        actualizaListaCaracteristicas(s, " where t.TCategoriaArticulo.id = '"+articulo.getId()+"' and t.TTipoCaracteristica.denominacion like '%"+buscarCA+"%'");
    }
    
    @NotifyChange({"articulo","verSave","articulos","val"})
    @Command()
    public void guardar() {
        System.out.println("guardar");
        //Asignacion de IDs
        if (saveLabel.equals("Guardar")) {
            //Asignacion de IDs
            articulo.setId(idNew.id());
        }
        articulo.setTClaseArticulo(claseSelected);
        if ((val.equals("")) && (articulo.getTClaseArticulo() == null)){
            articulo.setTClaseArticulo(null);
        }else if ((val.equals("")) && (articulo.getTClaseArticulo().getId() == null)){
            articulo.setTClaseArticulo(null);
        }
        
        Transaction tr = s.beginTransaction();
        tr.begin();
        dao.persist(s, articulo);
        tr.commit();
        verSave = false;
        actualizaListaArticulos(s, "");
        System.out.println("fin guarda");
        return;
    }
    
    @NotifyChange({"caracteristica","verSaveCA","caracteristicas","valCA","error"})
    @Command()
    public void guardarCA() {
        System.out.println("guardar Caracteristica");
        //Asignacion de IDs
        if (saveLabelCA.equals("Guardar")) {
            //Asignacion de IDs
            caracteristica.setIdCaractArt(idNew.id());
//        } else {
            
        }
        if (valCA.equals("")){
            error="No permitido, Agregar Tipo Caracteristica";
            return;
        }else{
            if (!(tipoSelected != null)){
                tipoSelected = new TTipoCaracteristica();
                tipoSelected.setId(idNew.id());
                tipoSelected.setDenominacion(valCA);
            }
            
        }
        caracteristica.setTTipoCaracteristica(tipoSelected);
        caracteristica.setTCategoriaArticulo(articulo);
        Transaction tr = s.beginTransaction();
        tr.begin();
        dao.persist(s, caracteristica);
        tr.commit();
        verSaveCA = false;
        actualizaListaCaracteristicas(s, " where t.TCategoriaArticulo.id = '"+articulo.getId()+"'");
        System.out.println("fin guarda");
        error="";
        return;
    }
    
    @NotifyChange({"verSave","articulo","mostrarAdd","saveLabel","saveLabelCA","clases", "val", "claseSelected", "mostrarCA"})
    @Command()
    public void edita(@BindingParam("art") TCategoriaArticulo art ) {
        System.out.println("editar");
        verSave = true;
        articulo = new TCategoriaArticulo();   
        articulo = (TCategoriaArticulo) dao.load(s, TCategoriaArticulo.class, art.getId()+"");
        articulo.setTClaseArticulo((TClaseArticulo) dao.load(s, TClaseArticulo.class, articulo.getTClaseArticulo().getId()+""));
        val="";
        actualizaListaClases(s, "");
        claseSelected = articulo.getTClaseArticulo();
        mostrarAdd = true;
        mostrarCA = true;
        saveLabelCA = "Modificar";
        saveLabel = "Modificar";
        
    }
    
    @NotifyChange({"verSaveCA","caracteristica","mostrarAddCA","saveLabelCA","tipos", "valCA", "tipoSelected", "mostrarCA"})
    @Command()
    public void editaCA(@BindingParam("carac") TCaracteristicasArticulo car ) {
        System.out.println("editar");
        verSaveCA = true;
        caracteristica = new TCaracteristicasArticulo();   
        caracteristica = (TCaracteristicasArticulo) dao.load(s, TCaracteristicasArticulo.class, car.getIdCaractArt()+"");
        caracteristica.setTTipoCaracteristica((TTipoCaracteristica) dao.load(s, TTipoCaracteristica.class, caracteristica.getTTipoCaracteristica().getId()+""));
        valCA="";
        actualizaListaTipos(s, "");
        tipoSelected = caracteristica.getTTipoCaracteristica();
        mostrarAddCA = true;
        mostrarCA = true;
        saveLabelCA = "Modificar";
        
    }
    
    @NotifyChange({"articulo","mostrarAdd","saveLabel","articulos"})
    @Command()
    public void elimina(@BindingParam("art") TCategoriaArticulo ar ) {
        System.out.println("eliminar");
        articulo = ar;
        Transaction tr = s.beginTransaction();
        tr.begin();
        dao.delete(s,articulo);
        tr.commit();
        mostrarAdd = false;
        actualizaListaArticulos(s,"");
    }
    
    @NotifyChange({"caracteristica","mostrarAddCA","saveLabelCA","caracteristicas"})
    @Command()
    public void eliminaCA(@BindingParam("carac") TCaracteristicasArticulo car ) {
        System.out.println("eliminar");
        caracteristica = car;
        Transaction tr = s.beginTransaction();
        tr.begin();
        dao.delete(s,caracteristica);
        tr.commit();
        mostrarAddCA = false;
        actualizaListaCaracteristicas(s, " where t.TCategoriaArticulo.id = '"+articulo.getId()+"'");
    }
    
    // Change Selected
    @NotifyChange({"articulo","mostrarAdd","clases","articuloSelected","val","verSave","mostrarCA","caracteristicas", "mostrarAddCA"})
    @Command()
    public void selecciona() {
        System.out.println("Selecciona almacen");
        verSave = false;
        articulo = new TCategoriaArticulo();
        clases = new LinkedList<TClaseArticulo>();
        val = "";
        actualizaListaClases(s,"");
        actualizaListaCaracteristicas(s, " where t.TCategoriaArticulo.id = '"+articuloSelected.getId()+"'");
        articulo = articuloSelected;
        claseSelected = articulo.getTClaseArticulo();
        mostrarAdd = true;
        mostrarAddCA = false;
        mostrarCA = true;
    }
    
    @NotifyChange({"articulo","verSave","mostrarAdd","clases","articuloSelected","val"})
    @Command()
    public void seleccionaCA() {
        System.out.println("Selecciona Caracteristica");
        verSaveCA = false;
        caracteristica = new TCaracteristicasArticulo();
        tipos = new LinkedList<TTipoCaracteristica>();
        valCA = "";
        actualizaListaTipos(s,"");
        caracteristica = caracteristicaSelected;
        tipoSelected = caracteristica.getTTipoCaracteristica();
        mostrarAdd = true;
    }
    
    
    // Metodos
    private void actualizaListaArticulos(Session s, String sql) {
        articulos.clear();
        articulos = dao.findAll(s, "from TCategoriaArticulo a" + sql);
    }
    
    private void actualizaListaCaracteristicas(Session s, String sql) {
        caracteristicas.clear();
        caracteristicas = dao.findAll(s, "from TCaracteristicasArticulo t" + sql);
    }
    
    private void actualizaListaClases(Session s, String sql) {
        clases.clear();
        clases = dao.findAll(s, "from TClaseArticulo c" + sql);
    }
    
    private void actualizaListaTipos(Session s, String sql) {
        tipos.clear();
        tipos = dao.findAll(s, "from TTipoCaracteristica c" + sql);
    }

    public List<TCategoriaArticulo> getArticulos() {
        return articulos;
    }

    public void setArticulos(List<TCategoriaArticulo> articulos) {
        this.articulos = articulos;
    }

    public List<TClaseArticulo> getClases() {
        return clases;
    }

    public void setClases(List<TClaseArticulo> clases) {
        this.clases = clases;
    }

    public TCategoriaArticulo getArticulo() {
        return articulo;
    }

    public void setArticulo(TCategoriaArticulo articulo) {
        this.articulo = articulo;
    }

    public TCategoriaArticulo getArticuloSelected() {
        return articuloSelected;
    }

    public void setArticuloSelected(TCategoriaArticulo articuloSelected) {
        this.articuloSelected = articuloSelected;
    }

    public TClaseArticulo getClaseSelected() {
        return claseSelected;
    }

    public void setClaseSelected(TClaseArticulo claseSelected) {
        this.claseSelected = claseSelected;
    }

    public boolean isVerSave() {
        return verSave;
    }

    public void setVerSave(boolean verSave) {
        this.verSave = verSave;
    }

    public boolean isMostrarAdd() {
        return mostrarAdd;
    }

    public void setMostrarAdd(boolean mostrarAdd) {
        this.mostrarAdd = mostrarAdd;
    }

    public String getSaveLabel() {
        return saveLabel;
    }

    public void setSaveLabel(String saveLabel) {
        this.saveLabel = saveLabel;
    }

    public String getBuscar() {
        return buscar;
    }

    public void setBuscar(String buscar) {
        this.buscar = buscar;
    }

    public String getVal() {
        return val;
    }

    public void setVal(String val) {
        this.val = val;
    }

    public Map<String, String> getValidationMessages() {
        return validationMessages;
    }

    public void setValidationMessages(Map<String, String> validationMessages) {
        this.validationMessages = validationMessages;
    }

    public List<TCaracteristicasArticulo> getCaracteristicas() {
        return caracteristicas;
    }

    public void setCaracteristicas(List<TCaracteristicasArticulo> caracteristicas) {
        this.caracteristicas = caracteristicas;
    }

    public List<TTipoCaracteristica> getTipos() {
        return tipos;
    }

    public void setTipos(List<TTipoCaracteristica> tipos) {
        this.tipos = tipos;
    }

    public TCaracteristicasArticulo getCaracteristica() {
        return caracteristica;
    }

    public void setCaracteristica(TCaracteristicasArticulo caracteristica) {
        this.caracteristica = caracteristica;
    }

    public TCaracteristicasArticulo getCaracteristicaSelected() {
        return caracteristicaSelected;
    }

    public void setCaracteristicaSelected(TCaracteristicasArticulo caracteristicaSelected) {
        this.caracteristicaSelected = caracteristicaSelected;
    }

    public TTipoCaracteristica getTipoSelected() {
        return tipoSelected;
    }

    public void setTipoSelected(TTipoCaracteristica tipoSelected) {
        this.tipoSelected = tipoSelected;
    }

    public boolean isVerSaveCA() {
        return verSaveCA;
    }

    public void setVerSaveCA(boolean verSaveCA) {
        this.verSaveCA = verSaveCA;
    }

    public boolean isMostrarAddCA() {
        return mostrarAddCA;
    }

    public void setMostrarAddCA(boolean mostrarAddCA) {
        this.mostrarAddCA = mostrarAddCA;
    }

    public String getSaveLabelCA() {
        return saveLabelCA;
    }

    public void setSaveLabelCA(String saveLabelCA) {
        this.saveLabelCA = saveLabelCA;
    }

    public String getBuscarCA() {
        return buscarCA;
    }

    public void setBuscarCA(String buscarCA) {
        this.buscarCA = buscarCA;
    }

    public String getValCA() {
        return valCA;
    }

    public void setValCA(String valCA) {
        this.valCA = valCA;
    }

    public boolean isMostrarCA() {
        return mostrarCA;
    }

    public void setMostrarCA(boolean mostrarCA) {
        this.mostrarCA = mostrarCA;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

}
